package com.example.birthday_getway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;

import java.util.Arrays;

@Configuration
public class CorsConfig {

  @Bean
  public CorsWebFilter corsWebFilter() {
    CorsConfiguration config = new CorsConfiguration();

    // 设置允许的来源
    config.setAllowedOrigins(Arrays.asList("http://127.0.0.1:5666", "http://localhost:5666"));

    // 设置允许的方法
    config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));

    // 设置允许的头部
    config.setAllowedHeaders(Arrays.asList("*"));

    // 允许携带凭证
    config.setAllowCredentials(true);

    // 设置预检请求缓存时间
    config.setMaxAge(3600L);

    // 创建基于URL的CORS配置源
    UrlBasedCorsConfigurationSource source =
        new UrlBasedCorsConfigurationSource(new PathPatternParser());
    source.registerCorsConfiguration("/**", config);

    return new CorsWebFilter(source);
  }
}
